﻿using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using He.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Media;
using He.Common;
using System.Text.RegularExpressions;
using System.Data;
using System.Web;
namespace He.Web.UI
{
    /// <summary>
    /// 前台页面的父类
    /// </summary>
    public partial class Front : PageBase
    {
        public Model.webset siteConfig;
        public Model.site_info siteInfo;
        public string webTitle;
        public Front()
        {
            siteConfig = webset;

            if (HttpContext.Current.Request.Path.ToLower().Contains("/m/") || (!string.IsNullOrEmpty(siteConfig.mobile_url) && HttpContext.Current.Request.Url.Authority.ToLower().Contains(siteConfig.mobile_url.ToLower().Replace("http://", ""))))
            {
                siteInfo = new BLL.site_info().GetModelByLang("mobile");
            }
            else if (HttpContext.Current.Request.Path.ToLower().Contains("/en/"))
            {
                siteInfo = new BLL.site_info().GetModelByLang("en");
            }
            else
            {
                siteInfo = new BLL.site_info().GetModelByLang("cn");
            }
            webTitle = siteInfo.WebTitle;
        }

        #region 网站标题信息

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string WebTitle()
        {
            return webTitle;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="classTitle"></param>
        /// <returns></returns>
        public string WebTitle(string category)
        {
            StringBuilder strTxt = new StringBuilder();
            strTxt.Append(category);
            strTxt.Append(" - ");
            strTxt.Append(webTitle);
            return strTxt.ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="classTitle"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public string WebTitle(string category, string title)
        {
            StringBuilder strTxt = new StringBuilder();
            strTxt.Append(title);
            strTxt.Append(" - ");
            strTxt.Append(category);
            strTxt.Append(" - ");
            strTxt.Append(webTitle);
            return strTxt.ToString();
        }

        #endregion

        #region Meta信息
        /// <summary>
        /// 返回页面Meta信息
        /// </summary>
        public string AddMetaInfo(string keywords, string description)
        {
            keywords = Server.HtmlEncode(keywords);
            description = Server.HtmlEncode(description);

            if (string.IsNullOrEmpty(keywords))
            {
                keywords = siteInfo.WebKeyWords;
            }
            if (string.IsNullOrEmpty(description))
            {
                description = siteInfo.WebDescription;
            }

            StringBuilder strTxt = new StringBuilder();
            strTxt.Append("<meta name=\"keywords\" content=\"" + keywords + "\" />\n");
            strTxt.Append("<meta name=\"description\" content=\"" + description + "\" />");
            return strTxt.ToString();
        }
        #endregion

        #region Url重写
        /// <summary>
        /// 返回伪静态统一链接地址
        /// </summary>
        public string UrlRewrite(string _key, params object[] _params)
        {
            //Hashtable _siteurls = new He.BLL.SiteUrl().loadConfig(Utils.GetXmlMapPath("Urlspath"));
            Hashtable _siteurls = new He.BLL.SiteUrlManager().loadConfig(PathHelper.MapXmlPath("Urlspath"));
            Model.SiteUrl model = _siteurls[_key] as Model.SiteUrl;
            if (model == null)
            {
                return "";
            }
            try
            {
                string _rewriteurl = string.Format(model.Path, _params);
                if (siteConfig.url_mode == (int)Enums.UrlMode.aspx伪静态 || siteConfig.url_mode == (int)Enums.UrlMode.html伪静态)
                {
                    return siteConfig.web_path.TrimEnd('/') + _rewriteurl;
                }
                string _originalurl = model.Page;
                if (!string.IsNullOrEmpty(model.QueryString))
                {
                    _originalurl = model.Page + "?" + Regex.Replace(_rewriteurl, model.Pattern, model.QueryString, RegexOptions.None | RegexOptions.IgnoreCase);
                }
                return siteConfig.web_path.TrimEnd('/') + _originalurl;
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 组合SQL语句

        /// <summary>
        /// 返回查询条件语句
        /// </summary>
        /// <param name="_channel_id">栏目ID</param>
        /// <param name="_category_id">类别ID</param>
        /// <returns>查询条件语句</returns>
        public string CombSqlTxt(int _channel_id, int _category_id)
        {
            StringBuilder strTemp = new StringBuilder();
            strTemp.Append("is_lock=0 ");
            strTemp.AppendFormat("and category_id in(select id from {0}category where channel_id={1}) ", SysKeys.TABLE_PREFIX, _channel_id);
            if (_category_id > 0)
            {
                strTemp.Append("and category_id in(select Id from he_category where id_list like '%," + _category_id + ",%') ");
            }
            return strTemp.ToString();
        }

        public string CombSqlTxt(int _channel_id, int _category_id, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            strTemp.Append("is_lock=0 ");
            strTemp.AppendFormat("and category_id in(select id from {0}category where channel_id={1}) ", SysKeys.TABLE_PREFIX, _channel_id);
            if (_category_id > 0)
            {
                strTemp.Append("and category_id in(select id from he_category where id_list like '%," + _category_id + ",%') ");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("and title like '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }

        #endregion

        #region 组合URL语句


        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_name">栏目名称</param>
        /// <param name="_category_id">类别ID</param>
        /// <param name="_keywords">关键字</param>
        /// <returns>返回URL语句</returns>
        public string CombUrlTxt(string _name, int _category_id, string _keywords)
        {
            //不含搜索关键词用重新模式
            if (string.IsNullOrEmpty(_keywords))
            {
                return RewriteUrl(_name, _category_id);
            }
            //含搜索关键词用普通模式
            else
            {
                StringBuilder strTemp = new StringBuilder();
                strTemp.AppendFormat("index.aspx?p=list&name={0}&page=__id__", _name);
                _keywords = _keywords.Replace("'", "");
                if (_category_id > 0)
                {
                    strTemp.Append("&category_id=" + _category_id);
                }
                if (!string.IsNullOrEmpty(_keywords))
                {
                    strTemp.Append("&keywords=" + Server.UrlEncode(_keywords));
                }
                return strTemp.ToString();
            }
        }
        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_channel_id">栏目ID</param>
        /// <param name="_category_id">类别ID</param>
        /// <param name="_keywords">关键字</param>
        /// <param name="_page_name">当前页面名</param>
        /// <returns>返回URL语句</returns>
        public string CombUrlTxt(string _name, int _category_id, string _keywords, string _page_name)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            strTemp.Append(_page_name + "?page=__id__");
            strTemp.Append("&name=" + _name);
            if (_category_id > 0)
            {
                strTemp.Append("&category_id=" + _category_id);
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("&keywords=" + Server.UrlEncode(_keywords));
            }
            return strTemp.ToString();
        }

        /// <summary>
        /// 重新URL
        /// </summary>
        /// <param name="_channel_id"></param>
        /// <param name="_category_id"></param>
        /// <returns></returns>
        public string RewriteUrl(string _name, int _category_id)
        {
            StringBuilder strTemp = new StringBuilder();
            return HtmlHelper.url("list", _name, _category_id, "__id__");
        }
        #endregion

        #region 判断是否手机浏览器
        public bool IsMobile()
        {
            HttpBrowserCapabilities bc = Request.Browser;
            string sl = bc.Browser;
            string agent = (Request.UserAgent + "").ToLower().Trim();

            string reg = @"mini 9.5|vx1000|lge |m800|e860|u940|ux840|compal|wireless| mobi|ahong|lg380|lgku|lgu900|lg210|lg47|lg920|lg840|lg370|sam-r|mg50|s55|g83|t66|vx400|mk99|d615|d763|el370|sl900|mp500|samu3|samu4|vx10|xda_|samu5|samu6|samu7|samu9|a615|b832|m881|s920|n210|s700|c-810|_h797|mob-x|sk16d|848b|mowser|s580|r800|471x|v120|rim8|c500foma:|160x|x160|480x|x640|t503|w839|i250|sprint|w398samr810|m5252|c7100|mt126|x225|s5330|s820|htil-g1|fly v71|s302|-x113|novarra|k610i|-three|8325rc|8352rc|sanyo|vx54|c888|nx250|n120|mtk |c5588|s710|t880|c5005|i;458x|p404i|s210|c5100|teleca|s940|c500|s590|foma|samsu|vx8|vx9|a1000|_mms|myx|a700|gu1100|bc831|e300|ems100|me701|me702m-three|sd588|s800|8325rc|ac831|mw200|brew |d88|htc\/|htc_touch|355x|m50|km100|d736|p-9521|telco|sl74|ktouch|m4u\/|me702|8325rc|kddi|phone|lg |sonyericsson|samsung|240x|x320vx10|nokia|sony cmd|motorola|up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|psp|treo|iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile|ipod|iphone|android|opera mini|blackberry|palm os|palm|hiptop|avantgo|fennec|plucker|xiino|blazer|elaine|iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile";
            if (agent.Contains("mobile"))
            {
                return true;
            }

            if (agent.Contains("windows nt"))
            {
                if (sl != "IE" && sl != "Firefox")
                {
                    if (System.Text.RegularExpressions.Regex.IsMatch(Request.ServerVariables["HTTP_USER_AGENT"], reg, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        return true;
                    }

                }
            }
            else
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 301跳转
        public void RedirectBy301(string url)
        {
            Response.Status = "301 Moved Permanently";
            Response.AddHeader("Location", url);
        }
        #endregion

        #region 获取页数
        public int GetPageCount(int rcount, int psize)
        {
            if (rcount % psize == 0)
            {
                return rcount / psize;
            }
            else
            {
                return rcount / psize + 1;
            }
        }
        public int GetPrevPage(int page, int pcount)
        {
            if (page <= 0)
            {
                return 0;
            }
            else if (page >= pcount)
            {
                return pcount;
            }
            return page - 1;
        }
        public int GetNextPage(int page, int pcount)
        {
            if (page <= 0)
            {
                return 0;
            }
            else if (page >= pcount)
            {
                return pcount;
            }
            return page + 1;
        }
        #endregion

        #region 频道信息
        /// <summary>
        /// 获取频道标题
        /// </summary>
        /// <param name="channel_id">频道ID</param>
        /// <returns></returns>
        public string GetChannelTitle(int channel_id)
        {
            He.BLL.channel bll = new BLL.channel();
            He.Model.channel model = bll.GetModelByCache(channel_id);
            return model.title;
        }
        #endregion

        #region 会员相关
        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <returns></returns>
        public string GetUserName()
        {
            //if (Session["UserName"] != null)
            //{
            //    return Session["UserName"].ToString();
            //}
            He.BLL.member bll = new BLL.member();
            string UserName = Server.UrlDecode(CookieHelper.Get("UserName"));
            string UserPwd = CookieHelper.Get("UserPwd");
            if (bll.Exists(UserName, UserPwd))
            {
                return UserName;
            }
            return string.Empty;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="gotoUrl"></param>
        public void Loginout(string gotoUrl)
        {
            //Session["UserName"] = null;
            CookieHelper.Remove("UserName");
            CookieHelper.Remove("UserPwd");
            Response.Redirect(gotoUrl);
        }
        #endregion

        #region  扩展属性
        public string GetAttrValue(object picId, object fieldId)
        {
            Model.attr_value model = new BLL.attr_value().GetModel("pictureid=" + picId + " and fieldid=" + fieldId);
            if (model != null)
            {
                return model.content;
            }
            return string.Empty;
        }
        public string GetAttrField(int fieldId)
        {
            Model.attr_field model = new BLL.attr_field().GetModel(fieldId);
            if (model != null)
            {
                return model.title;
            }
            return string.Empty;
        }
        #endregion

    }
}
